package apigateway.project.core.context;

import apigateway.project.commen.config.Rule;
import apigateway.project.core.request.GlobalRequest;
import apigateway.project.core.response.GlobalResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import lombok.Data;

import java.util.concurrent.atomic.AtomicBoolean;

@Data
public class GlobalContext {

    private ChannelHandlerContext ctx;

    private Rule rule;

    private boolean isPredicate=true;

    public boolean failPredicate(){
        return !isPredicate;
    }

    private GlobalRequest request;

    private GlobalResponse reponse;

    private volatile int status;
    public static class status_type{
        public static int RUNNING =0;
        public static int WRITTEN =1;
        public static int COMPLETED =2;
        public static int TERMINATED =3;
    }
    public void running (){
        status = status_type.RUNNING;
    }
    public void written(){
        status = status_type.WRITTEN;
    }
    public void completed(){
        status = status_type.COMPLETED;
    }
    public void terminated(){
        status = status_type.TERMINATED;
    }
    /**
     * 重试次数
     */
    private int currentRetryTimes;
    /**
     * 是否保持长连接
     */
    private boolean keepAlive;

    private AtomicBoolean isReleased = new AtomicBoolean(false);

    /**
     * 释放请求
     * @param
     */
    public void releaseRequest(){
        if(isReleased.compareAndExchange(false,true)){
            ReferenceCountUtil.release(request.getHttpRequest());

        }
    }

    public GlobalContext(ChannelHandlerContext ctx, boolean keepAlive, GlobalRequest request, Rule rule, int currentRetryTimes) {
        this.ctx = ctx;
        this.rule = rule;
        this.request = request;
        this.currentRetryTimes = currentRetryTimes;
        this.keepAlive = keepAlive;
    }

    /**
     * 测试
     * @param rule
     */
    public GlobalContext(Rule rule){
        this.rule = rule;
    }


}
